<template>
  <layout 
    tabbar="/pages/message/index" 
    navbar="none" 
    :showBack="false" 
    class="dark-theme"
    navbarBackgroundColor="#020303"
  >
    <view class="message-page">
      <!-- 移除原来的电竞风格背景光效，使用与首页一致的纯色背景 -->
      
      <!-- 自定义顶部导航区域 -->
      <view :style="{paddingTop: vuex_status_bar_height + 22 + 'px' }" class="custom-nav tn-flex tn-flex-col-center tn-flex-row-between">
        <view class="nav-tabs">
          <view 
            class="nav-tab" 
            :class="{ active: activeTabIndex === 0 }"
            @tap="changeTab(0)"
          >
            聊天
          </view>
          <view 
            class="nav-tab" 
            :class="{ active: activeTabIndex === 1 }"
            @tap="changeTab(1)"
          >
            群聊
          </view>
        </view>
        <view class="header-right">
          <!-- 预留右侧位置，保持布局平衡 -->
        </view>
      </view>
      
	  <z-paging-swiper> 
		  <swiper class="swiper" :current="activeTabIndex" @transition="swiperTransition" @animationfinish="swiperAnimationfinish">
		    <!-- 私聊消息列表 -->
		    <swiper-item>
		      <!-- 使用z-paging替代原来的scroll-view -->
		      <z-paging 
		        ref="chatPaging" 
		        v-model="messages" 
		        @query="queryChatMessages"
		        :default-page-size="10"
		        :auto="true"
		  			:paging-style="{paddingTop: vuex_status_bar_height + 44 + 'px'}"
		        :bg-color="'#020303'"
		        :loading-more-enabled="true"
		        :show-refresher-when-reload="true"
		        :refresher-threshold="80"
		        :refresher-default-text="'下拉刷新'"
		        :refresher-pulling-text="'释放立即刷新'"
		        :refresher-refreshing-text="'加载中...'"
		        :loading-more-custom-style="{color: '#B3F73C'}"
		        :show-loading-more-no-more-view="false"
		        :hide-loading-more-when-no-more-and-inside-of-paging="true"
		        :empty-view-text="'暂无消息'"
		        :empty-view-reload-text="'点击刷新'"
		        :show-empty-view-reload="true"
		        :auto-show-back-to-top="true"
		        :auto-clean-list-when-reload="true"
		      >
		  			
				<!-- 消息分类标签 -->
				<template #top>
				  <view class="message-tabs">
					<view 
					  v-for="(tab, index) in messageTabs" 
					  :key="index"
					  class="message-tab" 
					  :class="{ active: activeTab === tab.id }"
					  @tap="setActiveTab(tab.id)"
					>
					  {{ tab.name }}
					</view>
				  </view>
				</template>
				
				<template #bottom>
					<view style="height: 100rpx;"></view>
				</template>
		  			
		        <!-- 消息列表内容 -->
		        <view class="message-container">
		          <!-- 置顶消息 -->
		          <template v-if="pinnedMessages.length > 0">
		            <view 
		              v-for="message in pinnedMessages" 
		              :key="message.id" 
		              class="message-item"
		              @tap="goToChat(message)"
		              @longpress="showMessageOptions(message, $event)"
		              :class="{ 'pinned': true, 'muted': message.isMuted, 'vip-message': message.isVip }"
		            >
		              <view class="avatar">
		                <image :src="message.avatar" :alt="message.username" mode="aspectFill"></image>
		                <view class="online-indicator" v-if="message.isOnline"></view>
		                <view class="muted-indicator" v-if="message.isMuted">
		                  <text class="tn-icon-sound-close"></text>
		                </view>
		              </view>
		              <view class="message-content">
		                <view class="message-header">
		                  <view class="username-container">
		                    <view class="username" :class="{ 'username-vip': message.isVip }">{{ message.username }}</view>
		                    <view v-if="message.intimacy > 0" class="intimacy-indicator" :class="'intimacy-level-' + message.intimacy">
		                      <text class="tn-icon-like-fill"></text>
		                      <text>{{message.intimacy}}</text>
		                    </view>
		                  </view>
		                  <view class="time-container">
		                    <view class="time">{{ message.time }}</view>
		                  </view>
		                </view>
		                <view class="message-preview" :class="{ 'message-muted': message.isMuted }">
		                  {{ message.lastMessage }}
		                </view>
		              </view>
		              <view class="message-status">
		                <view class="unread-badge" v-if="message.unreadCount > 0">
		                  {{ message.unreadCount }}
		                </view>
		              </view>
		            </view>
		          </template>
		          
		          <!-- 非置顶消息 -->
		          <template v-for="(messageList, timeCategory) in categorizedMessages">
		            <view :key="timeCategory" v-if="messageList.length > 0">
		              <view class="new-message-label">
		                {{ timeCategoryLabel[timeCategory] || timeCategory }}
		              </view>
		              <view 
		                v-for="message in messageList" 
		                :key="message.id" 
		                class="message-item"
		                @tap="goToChat(message)"
		                @longpress="showMessageOptions(message, $event)"
		                :class="{ 'muted': message.isMuted, 'vip-message': message.isVip }"
		              >
		                <view class="avatar">
		                  <image :src="message.avatar" :alt="message.username" mode="aspectFill"></image>
		                  <view class="online-indicator" v-if="message.isOnline"></view>
		                  <view class="muted-indicator" v-if="message.isMuted">
		                    <text class="tn-icon-sound-close"></text>
		                  </view>
		                </view>
		                <view class="message-content">
		                  <view class="message-header">
		                    <view class="username-container">
		                      <view class="username" :class="{ 'username-vip': message.isVip }">{{ message.username }}</view>
		                      <view v-if="message.intimacy > 0" class="intimacy-indicator" :class="'intimacy-level-' + message.intimacy">
		                        <text class="tn-icon-like-fill"></text>
		                        <text>{{message.intimacy}}</text>
		                      </view>
		                    </view>
		                    <view class="time-container">
		                      <view class="time">{{ message.time }}</view>
		                    </view>
		                  </view>
		                  <view class="message-preview" :class="{ 'message-muted': message.isMuted }">
		                    {{ message.lastMessage }}
		                  </view>
		                </view>
		                <view class="message-status">
		                  <view class="unread-badge" v-if="message.unreadCount > 0">
		                    {{ message.unreadCount }}
		                  </view>
		                </view>
		              </view>
		            </view>
		          </template>
		        </view>
		      </z-paging>
		    </swiper-item>
		    
		    <!-- 群聊列表 -->
		    <swiper-item>
		      <!-- 使用z-paging替代原来的scroll-view -->
		      <z-paging 
		        ref="groupPaging" 
		        v-model="groupMessages" 
		        @query="queryGroupMessages"
		        :default-page-size="10"
		        :auto="true"
		        :bg-color="'#020303'"
		        :loading-more-enabled="true"
		        :show-refresher-when-reload="true"
		        :refresher-threshold="80"
		        :refresher-default-text="'下拉刷新'"
		        :refresher-pulling-text="'释放立即刷新'"
		        :refresher-refreshing-text="'加载中...'"
		        :loading-more-custom-style="{color: '#B3F73C'}"
		        :show-loading-more-no-more-view="false"
		        :hide-loading-more-when-no-more-and-inside-of-paging="true"
		        :empty-view-text="'暂无群聊'"
		        :empty-view-reload-text="'点击刷新'"
		        :show-empty-view-reload="true"
		        :auto-show-back-to-top="true"
		        :auto-clean-list-when-reload="true"
		        :fixed="false"
		        :paging-style="{paddingTop: vuex_status_bar_height + 44 + 'px'}"
		        :safe-area-inset-bottom="true"
		      >
		  		  
				<!-- 群聊选项卡 -->
				<template #top>
				  <view class="message-tabs">
					<view 
					  v-for="(tab, index) in groupTabs" 
					  :key="index"
					  class="message-tab" 
					  :class="{ active: activeGroupTab === tab.id }"
					  @tap="setActiveGroupTab(tab.id)"
					>
					  {{ tab.name }}
					</view>
				  </view>
				</template>
				
				<template #bottom>
					<view style="height: 100rpx;"></view>
				</template>
		  			
		        <view class="message-container">
		          <!-- 空状态显示 -->
		          <view v-if="groupMessages.length === 0" class="empty-state">
		            <view class="empty-icon">
		              <text class="tn-icon-team"></text>
		            </view>
		            <view class="empty-title">暂无群聊</view>
		            <view class="empty-desc">您目前没有加入任何群聊</view>
		            <view class="empty-action" @tap="goToCreateGroup">
		              <text class="tn-icon-add"></text>
		              <text>创建群聊</text>
		            </view>
		          </view>
		          
		          <!-- 置顶群聊 -->
		          <template v-if="pinnedGroupMessages.length > 0">
		            <view 
		              v-for="group in pinnedGroupMessages" 
		              :key="group.id" 
		              class="message-item pinned"
		              @tap="goToGroupChat(group)"
		              @longpress="showGroupOptions(group, $event)"
		              :class="{ 'muted': group.isMuted }"
		            >
		              <view class="avatar">
		                <image :src="group.avatar" :alt="group.name" mode="aspectFill"></image>
		                <view class="online-indicator" v-if="group.isActive"></view>
		                <view class="muted-indicator" v-if="group.isMuted">
		                  <text class="tn-icon-sound-close"></text>
		                </view>
		              </view>
		              <view class="message-content">
		                <view class="message-header">
		                  <view class="username-container">
		                    <view class="username">{{ group.name }}</view>
		                    <view v-if="group.memberCount" class="group-member-tag">
		                      <text class="tn-icon-team"></text>
		                      <text>{{ group.memberCount }}</text>
		                    </view>
		                  </view>
		                  <view class="time-container">
		                    <view class="time">{{ group.time }}</view>
		                  </view>
		                </view>
		                <view class="message-preview" :class="{ 'message-muted': group.isMuted }">
		                  <text v-if="group.lastSender" class="sender-name">{{ group.lastSender }}: </text>{{ group.lastMessage }}
		                </view>
		              </view>
		              <view class="message-status">
		                <view class="unread-badge" v-if="group.unreadCount > 0">
		                  {{ group.unreadCount }}
		                </view>
		              </view>
		            </view>
		          </template>
		          
		          <!-- 按时间分类的群聊列表 -->
		          <template v-for="(groupList, timeCategory) in categorizedGroupMessages">
		            <view :key="timeCategory" v-if="groupList.length > 0">
		              <view class="new-message-label">
		                {{ timeCategoryLabel[timeCategory] || timeCategory }}
		              </view>
		              <view 
		                v-for="group in groupList" 
		                :key="group.id" 
		                class="message-item"
		                @tap="goToGroupChat(group)"
		                @longpress="showGroupOptions(group, $event)"
		                :class="{ 'muted': group.isMuted }"
		              >
		                <view class="avatar">
		                  <image :src="group.avatar" :alt="group.name" mode="aspectFill"></image>
		                  <view class="online-indicator" v-if="group.isActive"></view>
		                  <view class="muted-indicator" v-if="group.isMuted">
		                    <text class="tn-icon-sound-close"></text>
		                  </view>
		                </view>
		                <view class="message-content">
		                  <view class="message-header">
		                    <view class="username-container">
		                      <view class="username">{{ group.name }}</view>
		                      <view v-if="group.memberCount" class="group-member-tag">
		                        <text class="tn-icon-team"></text>
		                        <text>{{ group.memberCount }}</text>
		                      </view>
		                    </view>
		                    <view class="time-container">
		                      <view class="time">{{ group.time }}</view>
		                    </view>
		                  </view>
		                  <view class="message-preview" :class="{ 'message-muted': group.isMuted }">
		                    <text v-if="group.lastSender" class="sender-name">{{ group.lastSender }}: </text>{{ group.lastMessage }}
		                  </view>
		                </view>
		                <view class="message-status">
		                  <view class="unread-badge" v-if="group.unreadCount > 0">
		                    {{ group.unreadCount }}
		                  </view>
		                </view>
		              </view>
		            </view>
		          </template>
		        </view>
		      </z-paging>
		    </swiper-item>
		  </swiper>
	  </z-paging-swiper>
      
      <!-- 上下文菜单 -->
      <view 
        class="context-menu" 
        v-if="contextMenuVisible" 
        :style="{
          left: contextMenuPosition.x + 'px',
          top: contextMenuPosition.y + 'px'
        }"
        @touchmove.stop.prevent
      >
        <view class="menu-item" @tap="togglePinMessage">
          <text class="tn-icon-task menu-icon"></text>
          <text>{{ selectedMessage && selectedMessage.isPinned ? '取消置顶' : '置顶聊天' }}</text>
        </view>
        <view class="menu-item" @tap="toggleMuteMessage">
          <text class="tn-icon-sound-close menu-icon"></text>
          <text>{{ selectedMessage && selectedMessage.isMuted ? '取消免打扰' : '消息免打扰' }}</text>
        </view>
        <view class="menu-item delete" @tap="deleteMessage">
          <text class="tn-icon-delete menu-icon"></text>
          <text>删除聊天</text>
        </view>
      </view>
      
      <!-- 点击遮罩关闭上下文菜单 -->
      <view 
        class="context-menu-mask" 
        v-if="contextMenuVisible"
        @tap="closeContextMenu"
        @touchmove.stop.prevent
      ></view>
    </view>
  </layout>
</template>

<script>
import { mapState } from 'vuex';
import router from '@/utils/router';

export default {
  name: 'MessagePage',
  data() {
    return {
      // 视图控制
      activeTabIndex: 0, // 0: chat, 1: group
      activeTab: 'all', // 'all', 'close' 或 'system'
      activeGroupTab: 'all', // 'all' 或 'recent'
      
      // 消息数据
      messages: [],
      groupMessages: [],
      
      // 原始消息数据，用于模拟数据库
      messagesOrigin: [],
      groupMessagesOrigin: [],
      
      // 加载状态
      isLoadingMore: false,
      isRefreshing: false,
      isLoadingMoreGroups: false,
      isRefreshingGroups: false,
      
      // 上下文菜单相关
      contextMenuVisible: false,
      contextMenuPosition: { x: 0, y: 0 },
      selectedMessage: null,
      
      // 高度计算
      swiperHeight: 500,
      scrollViewHeight: 400,
      
      // 搜索功能
      searchQuery: '',
      isSearchActive: false,
      
      // 时间分类标签
      timeCategoryLabel: {
        today: '今天',
        yesterday: '昨天',
        earlier: '更早'
      },
      
      // 新增的 messageTabs 数据
      messageTabs: [
        { id: 'all', name: '全部' },
        { id: 'close', name: '密友' },
        { id: 'system', name: '系统通知' }
      ],
      
      // 新增的 groupTabs 数据
      groupTabs: [
        { id: 'all', name: '全部' },
        { id: 'recent', name: '最近活跃' }
      ]
    };
  },
  computed: {
    ...mapState({
      vuex_status_bar_height: state => state.vuex_status_bar_height,
    }),
    
    // 筛选置顶消息
    pinnedMessages() {
      return this.messages.filter(msg => msg.isPinned);
    },
    
    // 筛选今天的消息
    todayMessages() {
      return this.messages.filter(msg => !msg.isPinned && msg.timeCategory === 'today');
    },
    
    // 筛选昨天的消息
    yesterdayMessages() {
      return this.messages.filter(msg => !msg.isPinned && msg.timeCategory === 'yesterday');
    },
    
    // 筛选更早的消息
    earlierMessages() {
      return this.messages.filter(msg => !msg.isPinned && msg.timeCategory === 'earlier');
    },
    
    // 分类消息
    categorizedMessages() {
      return {
        today: this.todayMessages,
        yesterday: this.yesterdayMessages,
        earlier: this.earlierMessages
      };
    },
    
    // 未读消息总数
    totalUnreadCount() {
      return this.messages.reduce((total, msg) => total + msg.unreadCount, 0);
    },
    
    // 筛选置顶群聊
    pinnedGroupMessages() {
      return this.groupMessages.filter(group => group.isPinned);
    },
    
    // 筛选今天的群聊
    todayGroupMessages() {
      return this.groupMessages.filter(group => !group.isPinned && group.timeCategory === 'today');
    },
    
    // 筛选昨天的群聊
    yesterdayGroupMessages() {
      return this.groupMessages.filter(group => !group.isPinned && group.timeCategory === 'yesterday');
    },
    
    // 筛选更早的群聊
    earlierGroupMessages() {
      return this.groupMessages.filter(group => !group.isPinned && group.timeCategory === 'earlier');
    },
    
    // 分类群聊消息
    categorizedGroupMessages() {
      return {
        today: this.todayGroupMessages,
        yesterday: this.yesterdayGroupMessages,
        earlier: this.earlierGroupMessages
      };
    }
  },
  mounted() {
    this.initData();
  },
  beforeDestroy() {
    // 移除无用的监听器代码
  },
  methods: {
    // 初始化数据
    initData() {
      // 模拟获取消息数据
      this.initMessagesOrigin();
    },
    
    // 初始化原始消息数据
    initMessagesOrigin() {
      // 模拟数据
      this.messagesOrigin = [
        {
          id: 1,
          username: '锦鲤抄',
          avatar: 'https://picsum.photos/seed/user1/100',
          lastMessage: '你好！我看了你的照片，感觉很有气质，想认识一下',
          time: '09:40',
          unreadCount: 2,
          isOnline: true,
          isPinned: true,
          isMuted: false,
          timeCategory: 'today',
          intimacy: 3,
          isVip: true
        },
        {
          id: 2,
          username: '阿萨德',
          avatar: 'https://picsum.photos/seed/user2/100',
          lastMessage: '哪里还有我们一起看过的那家美食店啊？',
          time: '10:23',
          unreadCount: 0,
          isOnline: true,
          isPinned: true,
          isMuted: false,
          timeCategory: 'today',
          intimacy: 5,
          isVip: true
        },
        {
          id: 3,
          username: '游戏快乐',
          avatar: 'https://picsum.photos/seed/user3/100',
          lastMessage: '晚上八点开黑，不见不散！',
          time: '08:15',
          unreadCount: 5,
          isOnline: false,
          isPinned: false,
          isMuted: false,
          timeCategory: 'today',
          intimacy: 4
        },
        {
          id: 4,
          username: '系统通知',
          avatar: 'https://picsum.photos/seed/system/100',
          lastMessage: '您的账户已通过高级认证，解锁更多特权功能！',
          time: '07:02',
          unreadCount: 1,
          isOnline: false,
          isPinned: false,
          isMuted: false,
          timeCategory: 'today',
          intimacy: 0
        },
        {
          id: 5,
          username: '小红',
          avatar: 'https://picsum.photos/seed/user4/100',
          lastMessage: '我们的游戏卡组已经创建好了，速度来参加吧~',
          time: '昨天',
          unreadCount: 0,
          isOnline: true,
          isPinned: false,
          isMuted: false,
          timeCategory: 'yesterday',
          intimacy: 2,
          isVip: true
        },
        {
          id: 6,
          username: '冰淇淋',
          avatar: 'https://picsum.photos/seed/user5/100',
          lastMessage: '图片',
          time: '昨天',
          unreadCount: 0,
          isOnline: false,
          isPinned: false,
          isMuted: true,
          timeCategory: 'yesterday',
          intimacy: 1
        },
        {
          id: 7,
          username: '活动推送',
          avatar: 'https://picsum.photos/seed/activity/100',
          lastMessage: '新的线下活动已发布，点击查看详情',
          time: '前天',
          unreadCount: 0,
          isOnline: false,
          isPinned: false,
          isMuted: false,
          timeCategory: 'earlier',
          intimacy: 0
        },
        {
          id: 8,
          username: '雪拉比',
          avatar: 'https://picsum.photos/seed/user6/100',
          lastMessage: '下周末有空吗？一起去看演唱会吧！',
          time: '上周',
          unreadCount: 0,
          isOnline: false,
          isPinned: false,
          isMuted: false,
          timeCategory: 'earlier',
          intimacy: 3,
          isVip: true
        }
      ];
      
      // 模拟群聊数据
      this.groupMessagesOrigin = [
        {
          id: 1,
          name: '游戏开黑群',
          avatar: 'https://picsum.photos/seed/group1/100',
          lastMessage: '今晚八点开黑，有人来吗？',
          lastSender: '小明',
          time: '09:40',
          unreadCount: 3,
          isActive: true,
          isPinned: true,
          isMuted: false,
          memberCount: 42,
          timeCategory: 'today'
        },
        {
          id: 2,
          name: '设计交流',
          avatar: 'https://picsum.photos/seed/group2/100',
          lastMessage: '分享一个最新的UI设计趋势',
          lastSender: '设计师小A',
          time: '昨天',
          unreadCount: 0,
          isActive: false,
          isPinned: false,
          isMuted: true,
          memberCount: 128,
          timeCategory: 'yesterday'
        },
        {
          id: 3,
          name: '周末活动群',
          avatar: 'https://picsum.photos/seed/group3/100',
          lastMessage: '这周末去爬山的举手！',
          lastSender: '活动组织者',
          time: '昨天',
          unreadCount: 12,
          isActive: true,
          isPinned: false,
          isMuted: false,
          memberCount: 56,
          timeCategory: 'yesterday'
        },
        {
          id: 4,
          name: '电竞赛事交流',
          avatar: 'https://picsum.photos/seed/group4/100',
          lastMessage: '今晚的比赛太精彩了！',
          lastSender: '电竞迷',
          time: '上周',
          unreadCount: 0,
          isActive: false,
          isPinned: false,
          isMuted: false,
          memberCount: 89,
          timeCategory: 'earlier'
        },
        {
          id: 5,
          name: '技术学习小组',
          avatar: 'https://picsum.photos/seed/group5/100',
          lastMessage: '我找到了一个非常好的学习资源，分享给大家',
          lastSender: '程序员小王',
          time: '上周',
          unreadCount: 0,
          isActive: true,
          isPinned: false,
          isMuted: false,
          memberCount: 35,
          timeCategory: 'earlier'
        }
      ];
    },
    
    // z-paging加载聊天消息
    queryChatMessages(pageNo, pageSize) {
      console.log(`加载聊天消息：第${pageNo}页，每页${pageSize}条`);
      
      // 模拟异步请求
      setTimeout(() => {
        // 根据选项卡筛选数据
        let filteredMessages = [...this.messagesOrigin];
        
        if (this.activeTab === 'close') {
          filteredMessages = filteredMessages.filter(msg => msg.intimacy >= 3);
        } else if (this.activeTab === 'system') {
          filteredMessages = filteredMessages.filter(msg => 
            msg.username.includes('系统') || 
            msg.username.includes('通知') || 
            msg.username.includes('活动')
          );
        }
        
        // 模拟生成更多数据
        if (pageNo > 1) {
          const newMessages = [];
          for (let i = 0; i < pageSize; i++) {
            const baseId = (pageNo - 1) * pageSize + i + this.messagesOrigin.length;
            newMessages.push({
              id: baseId,
              username: `用户${baseId}`,
              avatar: `https://picsum.photos/seed/user${baseId}/100`,
              lastMessage: `这是第${pageNo}页的消息${i + 1}`,
              time: '更早',
              unreadCount: 0,
              isOnline: false,
              isPinned: false,
              isMuted: false,
              timeCategory: 'earlier',
              intimacy: Math.floor(Math.random() * 5)
            });
          }
          
          // 将生成的新消息添加到原始数据中模拟数据库增长
          if (pageNo === 2) {
            this.messagesOrigin = [...this.messagesOrigin, ...newMessages];
            filteredMessages = [...filteredMessages, ...newMessages];
          } 
          // 如果是第3页及以上的数据，模拟已经没有更多数据了
          else if (pageNo >= 3) {
            filteredMessages = [];
          }
        }
        
        // 对数据进行分页
        const startIndex = (pageNo - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        const pageData = filteredMessages.slice(startIndex, endIndex);
        
        // 将数据传递给z-paging
        this.$refs.chatPaging.complete(pageData);
      }, 500);
    },
    
    // z-paging加载群聊消息
    queryGroupMessages(pageNo, pageSize) {
      console.log(`加载群聊消息：第${pageNo}页，每页${pageSize}条`);
      
      // 模拟异步请求
      setTimeout(() => {
        // 根据选项卡筛选数据
        let filteredGroups = [...this.groupMessagesOrigin];
        
        if (this.activeGroupTab === 'recent') {
          filteredGroups = filteredGroups.filter(group => group.isActive);
        }
        
        // 模拟生成更多数据
        if (pageNo > 1) {
          const newGroups = [];
          for (let i = 0; i < pageSize; i++) {
            const baseId = (pageNo - 1) * pageSize + i + this.groupMessagesOrigin.length;
            const timeCategory = i % 3 === 0 ? 'today' : (i % 3 === 1 ? 'yesterday' : 'earlier');
            newGroups.push({
              id: baseId,
              name: `群聊${baseId}`,
              avatar: `https://picsum.photos/seed/group${baseId}/100`,
              lastMessage: `这是第${pageNo}页的群聊消息${i + 1}`,
              lastSender: `成员${baseId}`,
              time: timeCategory === 'today' ? `${Math.floor(Math.random() * 12) + 1}:${Math.floor(Math.random() * 60)}` : 
                    (timeCategory === 'yesterday' ? '昨天' : '更早'),
              unreadCount: Math.floor(Math.random() * 5),
              isActive: Math.random() > 0.5,
              isPinned: false,
              isMuted: Math.random() > 0.8,
              memberCount: Math.floor(Math.random() * 100) + 20,
              timeCategory: timeCategory
            });
          }
          
          // 将生成的新群聊添加到原始数据中模拟数据库增长
          if (pageNo === 2) {
            this.groupMessagesOrigin = [...this.groupMessagesOrigin, ...newGroups];
            filteredGroups = [...filteredGroups, ...newGroups];
          } 
          // 如果是第3页及以上的数据，模拟已经没有更多数据了
          else if (pageNo >= 3) {
            filteredGroups = [];
          }
        }
        
        // 对数据进行分页
        const startIndex = (pageNo - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        const pageData = filteredGroups.slice(startIndex, endIndex);
        
        // 将数据传递给z-paging
        this.$refs.groupPaging.complete(pageData);
      }, 500);
    },
    
    // 切换标签页
    changeTab(index) {
      if (this.activeTabIndex !== index) {
        this.activeTabIndex = index;
        
        // 同步到swiper的current
        if (this.$refs.pagingSwiper) {
          this.$refs.pagingSwiper.current = index;
        }
        
        // 当切换到群聊时，触发群聊列表刷新
        if (index === 1 && this.$refs.groupPaging) {
          this.$nextTick(() => {
            this.$refs.groupPaging.reload();
          });
        } else if (index === 0 && this.$refs.chatPaging) {
          this.$nextTick(() => {
            this.$refs.chatPaging.reload();
          });
        }
      }
    },
    
    // 设置活动视图（兼容旧代码）
    setActiveView(view) {
      this.changeTab(view === 'chat' ? 0 : 1);
    },
    
    // 设置活动标签
    setActiveTab(tabId) {
      this.activeTab = tabId;
      console.log(`切换到消息标签: ${tabId}`);
      // 基于所选标签刷新消息列表
      this.$refs.chatPaging.reload();
    },
    
    // 设置群聊活动标签
    setActiveGroupTab(tabId) {
      this.activeGroupTab = tabId;
      console.log(`切换到群聊标签: ${tabId}`);
      // 基于所选标签刷新群聊列表
      this.$refs.groupPaging.reload();
    },
    
    // 跳转到聊天详情页
    goToChat(message) {
      // 标记该消息为已读
      if (message.unreadCount > 0) {
        const index = this.messages.findIndex(m => m.id === message.id);
        if (index !== -1) {
          this.messages[index].unreadCount = 0;
        }
        
        // 同时更新原始数据中的已读状态
        const originIndex = this.messagesOrigin.findIndex(m => m.id === message.id);
        if (originIndex !== -1) {
          this.messagesOrigin[originIndex].unreadCount = 0;
        }
      }
      
      // 跳转到聊天页面
      uni.navigateTo({
        url: `/pages/chat/index?id=${message.id}&username=${encodeURIComponent(message.username)}&isOnline=${message.isOnline}`
      });
    },
    
    // 跳转到群聊详情页
    goToGroupChat(group) {
      // 标记该群聊为已读
      if (group.unreadCount > 0) {
        const index = this.groupMessages.findIndex(g => g.id === group.id);
        if (index !== -1) {
          this.groupMessages[index].unreadCount = 0;
        }
        
        // 同时更新原始数据中的已读状态
        const originIndex = this.groupMessagesOrigin.findIndex(g => g.id === group.id);
        if (originIndex !== -1) {
          this.groupMessagesOrigin[originIndex].unreadCount = 0;
        }
      }
      
      // 跳转到群聊页面
      uni.navigateTo({
        url: `/pages/chat/group?id=${group.id}&name=${encodeURIComponent(group.name)}`
      });
    },
    
    // 显示上下文菜单
    showContextMenu(e) {
      // 获取点击位置
      const touch = e.touches[0];
      const windowWidth = uni.getSystemInfoSync().windowWidth;
      const windowHeight = uni.getSystemInfoSync().windowHeight;
      
      // 菜单宽度，300rpx转为px
      const menuWidth = 300 * (windowWidth / 750);
      
      // 计算菜单显示位置，避免超出屏幕
      let x = touch.clientX - 100; 
      let y = touch.clientY - 40;
      
      // 防止菜单超出屏幕右侧
      if (x + menuWidth > windowWidth) {
        x = windowWidth - menuWidth - 10;
      }
      
      // 防止菜单超出屏幕左侧
      if (x < 10) {
        x = 10;
      }
      
      // 菜单高度约 3个菜单项 * 80px
      const menuHeight = 240;
      
      // 防止菜单超出屏幕底部
      if (y + menuHeight > windowHeight) {
        y = windowHeight - menuHeight - 10;
      }
      
      // 防止菜单超出屏幕顶部
      if (y < 100) {
        y = 100;
      }
      
      this.contextMenuPosition = { x, y };
      this.contextMenuVisible = true;
    },
    
    // 关闭上下文菜单
    closeContextMenu() {
      this.contextMenuVisible = false;
      this.selectedMessage = null;
    },
    
    // 切换置顶状态
    togglePinMessage() {
      if (!this.selectedMessage) return;
      
      const isGroup = this.activeTabIndex === 1;
      
      if (isGroup) {
        // 更新当前数据
        const index = this.groupMessages.findIndex(g => g.id === this.selectedMessage.id);
        if (index !== -1) {
          this.groupMessages[index].isPinned = !this.groupMessages[index].isPinned;
          
          // 同时更新原始数据
          const originIndex = this.groupMessagesOrigin.findIndex(g => g.id === this.selectedMessage.id);
          if (originIndex !== -1) {
            this.groupMessagesOrigin[originIndex].isPinned = this.groupMessages[index].isPinned;
          }
        }
      } else {
        // 更新当前数据
        const index = this.messages.findIndex(m => m.id === this.selectedMessage.id);
        if (index !== -1) {
          this.messages[index].isPinned = !this.messages[index].isPinned;
          
          // 同时更新原始数据
          const originIndex = this.messagesOrigin.findIndex(m => m.id === this.selectedMessage.id);
          if (originIndex !== -1) {
            this.messagesOrigin[originIndex].isPinned = this.messages[index].isPinned;
          }
        }
      }
      
      this.closeContextMenu();
    },
    
    // 切换消息免打扰状态
    toggleMuteMessage() {
      if (!this.selectedMessage) return;
      
      const isGroup = this.activeTabIndex === 1;
      
      if (isGroup) {
        // 更新当前数据
        const index = this.groupMessages.findIndex(g => g.id === this.selectedMessage.id);
        if (index !== -1) {
          this.groupMessages[index].isMuted = !this.groupMessages[index].isMuted;
          
          // 同时更新原始数据
          const originIndex = this.groupMessagesOrigin.findIndex(g => g.id === this.selectedMessage.id);
          if (originIndex !== -1) {
            this.groupMessagesOrigin[originIndex].isMuted = this.groupMessages[index].isMuted;
          }
        }
      } else {
        // 更新当前数据
        const index = this.messages.findIndex(m => m.id === this.selectedMessage.id);
        if (index !== -1) {
          this.messages[index].isMuted = !this.messages[index].isMuted;
          
          // 同时更新原始数据
          const originIndex = this.messagesOrigin.findIndex(m => m.id === this.selectedMessage.id);
          if (originIndex !== -1) {
            this.messagesOrigin[originIndex].isMuted = this.messages[index].isMuted;
          }
        }
      }
      
      this.closeContextMenu();
    },
    
    // 删除消息或群聊
    deleteMessage() {
      if (!this.selectedMessage) return;
      
      const isGroup = this.activeTabIndex === 1;
      
      if (isGroup) {
        // 更新当前数据
        const index = this.groupMessages.findIndex(g => g.id === this.selectedMessage.id);
        if (index !== -1) {
          this.groupMessages.splice(index, 1);
          
          // 同时更新原始数据
          const originIndex = this.groupMessagesOrigin.findIndex(g => g.id === this.selectedMessage.id);
          if (originIndex !== -1) {
            this.groupMessagesOrigin.splice(originIndex, 1);
          }
        }
      } else {
        // 更新当前数据
        const index = this.messages.findIndex(m => m.id === this.selectedMessage.id);
        if (index !== -1) {
          this.messages.splice(index, 1);
          
          // 同时更新原始数据
          const originIndex = this.messagesOrigin.findIndex(m => m.id === this.selectedMessage.id);
          if (originIndex !== -1) {
            this.messagesOrigin.splice(originIndex, 1);
          }
        }
      }
      
      this.closeContextMenu();
    },
    
    // tabs通知swiper切换
    tabsChange(index) {
      this.activeTabIndex = index;
    },
    
    // swiper滑动中
    swiperTransition(e) {
      // 不处理过渡动画，保持简单
    },
    
    // 更新指示器位置的辅助方法
    updateIndicatorPosition(progress) {
      // 不再需要
    },
    
    // swiper滑动结束
    swiperAnimationfinish(e) {
      if (e && e.detail) {
        this.changeTab(e.detail.current);
      }
    },
    
    // 获取二级tab指示器位置
    getSecondaryTabPosition() {
      switch(this.activeTab) {
        case 'all':
          return '5rpx';
        case 'close':
          return 'calc(33.33% + 3rpx)';
        case 'system':
          return 'calc(66.66% + 1rpx)';
        default:
          return '5rpx';
      }
    },
    
    // 获取群聊tab指示器位置的方法
    getGroupTabPosition() {
      switch(this.activeGroupTab) {
        case 'all':
          return '5rpx';
        case 'recent':
          return 'calc(50% + 3rpx)';
        default:
          return '5rpx';
      }
    },
    
    // 跳转到创建群聊页面
    goToCreateGroup() {
      uni.navigateTo({
        url: '/pages/chat/createGroup'
      });
    },
    
    // 显示消息操作菜单
    showMessageOptions(message, e) {
      this.selectedMessage = message;
      this.showContextMenu(e);
    },
    
    // 显示群聊操作菜单
    showGroupOptions(group, e) {
      this.selectedMessage = group;
      this.showContextMenu(e);
    }
  }
}
</script>

<style lang="scss" scoped>
.swiper {
	height: 100%;
}
	
.message-page {
  background-color: #020303;
}

/* 自定义导航栏 */
.custom-nav {
  width: 100%;
  height: 88rpx;
  padding: 0 30rpx;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #020303;
  z-index: 10;
  
  .nav-tabs {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 60rpx;
  }
  
  .nav-tab {
    font-size: 32rpx;
    font-weight: 600;
    padding: 10rpx 0;
    position: relative;
    color: #888;
    transition: color 0.3s;
  }
  
  .nav-tab.active {
    color: #B3F73C;
  }
  
  .nav-tab.active::after {
    content: '';
    position: absolute;
    bottom: -4rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 40rpx;
    height: 6rpx;
    background-color: #B3F73C;
    border-radius: 6rpx;
  }
}

/* 消息选项卡样式 */
.message-tabs {
  display: flex;
  justify-content: flex-start;
  padding: 0 32rpx;
  margin: 20rpx 0 10rpx;
  gap: 30rpx;
  
  .message-tab {
    font-size: 28rpx;
    color: #888;
    padding: 6rpx 0;
    position: relative;
    transition: color 0.3s;
    
    &.active {
      color: #B3F73C;
      font-weight: 500;
      
      &::after {
        content: '';
        position: absolute;
        bottom: -2rpx;
        left: 0;
        right: 0;
        height: 4rpx;
        background-color: #B3F73C;
        border-radius: 4rpx;
      }
    }
  }
}

/* 消息页面的主要内容 */
.content-swiper {
  width: 100%;
  flex: 1;
  
  .swiper-slide {
    height: 100%;
    width: 100%;
    position: relative;
    display: flex;
    flex-direction: column;
  }
}

/* 消息容器 */
.message-container {
  padding: 20rpx 32rpx;
  
  .new-message-label {
    font-size: 28rpx;
    color: #888;
    margin: 20rpx 0 14rpx;
    padding-left: 20rpx;
    position: relative;
    
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 6rpx;
      height: 28rpx;
      background-color: #B3F73C;
      border-radius: 6rpx;
    }
  }
  
  .message-item {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx; /* 减小间隔，更紧凑 */
    padding: 28rpx; /* 稍微减小内边距 */
    background-color: #050505;
    border-radius: 32rpx;
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.3);
    transition: all 0.2s ease;
    position: relative;
    
    &:active {
      transform: scale(0.98);
      box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.2);
    }
    
    &.pinned {
      border-left: 6rpx solid #B3F73C;
      background-color: #0a0a0a;
      
      &::after {
        content: '';
        position: absolute;
        top: 20rpx;
        right: 20rpx;
        width: 20rpx;
        height: 20rpx;
        background-color: #B3F73C;
        border-radius: 50%;
        box-shadow: 0 0 10rpx rgba(179, 247, 60, 0.5);
      }
    }
    
    &.vip-message {
      background: linear-gradient(90deg, #050505, #0a0a0a);
      border: 1px solid rgba(179, 247, 60, 0.08);
    }
    
    .avatar {
      position: relative;
      margin-right: 24rpx;
      
      image {
        width: 88rpx;
        height: 88rpx;
        border-radius: 50%;
        object-fit: cover;
      }
      
      .online-indicator {
        position: absolute;
        bottom: 2rpx;
        right: 2rpx;
        width: 18rpx;
        height: 18rpx;
        background-color: #B3F73C;
        border-radius: 50%;
        border: 3rpx solid #050505;
        box-shadow: 0 0 10rpx rgba(179, 247, 60, 0.5);
      }
      
      .muted-indicator {
        position: absolute;
        bottom: 0;
        right: 0;
        width: 32rpx;
        height: 32rpx;
        background-color: rgba(5, 5, 5, 0.9);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1rpx solid rgba(255, 255, 255, 0.1);
        box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.3);
        
        .tn-icon-sound-close {
          font-size: 18rpx;
          color: #B3F73C; /* 使用与主题一致的颜色 */
        }
      }
    }
    
    .message-content {
      flex: 1;
      min-width: 0;
      margin-right: 16rpx;
      
      .message-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 6rpx;
        
        .username-container {
          display: flex;
          align-items: center;
          min-width: 0;
          
          .username {
            font-size: 30rpx;
            font-weight: 600;
            color: #ffffff;
            margin-right: 10rpx;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 300rpx;
            
            &.username-vip {
              background: linear-gradient(45deg, #8eac21, #B3F73C);
              background-size: 200% 200%;
              -webkit-background-clip: text;
              -webkit-text-fill-color: transparent;
              text-shadow: 0 0 5px rgba(179, 247, 60, 0.3);
              animation: gradient-animation 3s ease infinite;
              font-weight: 700;
            }
          }
          
          .intimacy-indicator {
            display: flex;
            align-items: center;
            font-size: 22rpx;
            padding: 2rpx 10rpx;
            border-radius: 20rpx;
            
            &.intimacy-level-1 {
              background-color: rgba(179, 247, 60, 0.1);
              color: #B3F73C;
            }
            
            &.intimacy-level-2 {
              background-color: rgba(179, 247, 60, 0.2);
              color: #B3F73C;
            }
            
            &.intimacy-level-3 {
              background-color: rgba(179, 247, 60, 0.3);
              color: #B3F73C;
            }
            
            .tn-icon-like-fill {
              margin-right: 4rpx;
              font-size: 24rpx;
            }
          }
        }
        
        .time-container {
          min-width: fit-content;
          
          .time {
            font-size: 24rpx;
            color: #888;
          }
        }
      }
      
      .message-preview {
        font-size: 28rpx;
        color: #e0e0e0;
        line-height: 1.4;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 450rpx;
        
        &.message-muted {
          color: #888;
        }
      }
    }
    
    .message-status {
      margin-left: 10rpx;
      min-width: 0;
      flex-shrink: 0;
      
      .unread-badge {
        background: #B3F73C;
        color: #020303;
        font-size: 24rpx;
        min-width: 40rpx; /* 稍微减小 */
        height: 40rpx; /* 稍微减小 */
        border-radius: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 12rpx; /* 减小内边距 */
        box-shadow: 0 4rpx 16rpx rgba(179, 247, 60, 0.4);
        font-weight: bold;
        position: relative;
        
        /* 未读消息闪烁效果 */
        &::after {
          content: '';
          position: absolute;
          top: -4rpx;
          left: -4rpx;
          right: -4rpx;
          bottom: -4rpx;
          border-radius: 24rpx;
          border: 2rpx solid rgba(179, 247, 60, 0.4);
          animation: pulse 1.5s infinite;
          pointer-events: none;
        }
      }
    }
  }
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 150rpx 40rpx 120rpx;
  text-align: center;
  
  .empty-icon {
    font-size: 100rpx;
    color: rgba(179, 247, 60, 0.2);
    margin-bottom: 30rpx;
    animation: float 3s ease-in-out infinite;
  }
  
  .empty-title {
    font-size: 32rpx;
    font-weight: 600;
    margin-bottom: 16rpx;
    color: #e0e0e0;
  }
  
  .empty-desc {
    font-size: 26rpx;
    max-width: 600rpx;
    line-height: 1.5;
    color: #888;
  }
}

/* z-paging相关样式调整 */
:deep(.z-paging-content) {
  background-color: transparent;
}

:deep(.z-paging-content-empty) {
  background-color: transparent;
}

:deep(.z-paging-refresher-title) {
  color: #B3F73C;
}

:deep(.z-paging-loading-more-text) {
  color: #B3F73C;
  opacity: 0.7;
}

:deep(.z-paging-back-to-top) {
  background: rgba(179, 247, 60, 0.2);
  box-shadow: 0 0 16rpx rgba(179, 247, 60, 0.3);
}

@keyframes gradient-animation {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

@keyframes float {
  0% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-15rpx);
  }
  100% {
    transform: translateY(0);
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 0.6;
  }
  70% {
    transform: scale(1.2);
    opacity: 0;
  }
  100% {
    transform: scale(1);
    opacity: 0;
  }
}

/* 添加特定于群聊的CSS样式 */
.group-member-tag {
  display: flex;
  align-items: center;
  font-size: 22rpx;
  color: #B3F73C;
  background-color: rgba(179, 247, 60, 0.08);
  padding: 2rpx 10rpx;
  border-radius: 20rpx;
  margin-left: 10rpx;
  
  .tn-icon-team {
    margin-right: 4rpx;
    font-size: 24rpx;
  }
}

.sender-name {
  color: #B3F73C;
  font-weight: 600;
  opacity: 0.9;
}

.empty-action {
  margin-top: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(90deg, #8eac21, #B3F73C);
  color: #050505;
  font-size: 28rpx;
  font-weight: 600;
  padding: 16rpx 40rpx;
  border-radius: 40rpx;
  box-shadow: 0 6rpx 20rpx rgba(179, 247, 60, 0.3);
  transition: all 0.2s ease;
  
  .tn-icon-add {
    margin-right: 10rpx;
    font-size: 30rpx;
  }
  
  &:active {
    transform: scale(0.95);
    box-shadow: 0 4rpx 10rpx rgba(179, 247, 60, 0.2);
  }
}

/* 上下文菜单样式 */
.context-menu {
  position: fixed;
  z-index: 9999;
  background-color: #1d1d1d;
  border-radius: 16rpx;
  width: 300rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.4);
  overflow: hidden;
  animation: context-menu-in 0.15s ease-out;
  border: 1px solid rgba(179, 247, 60, 0.1);
  
  @keyframes context-menu-in {
    from {
      opacity: 0;
      transform: scale(0.8);
    }
    to {
      opacity: 1;
      transform: scale(1);
    }
  }
  
  .menu-item {
    padding: 30rpx 28rpx;
    font-size: 28rpx;
    color: #e0e0e0;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    transition: all 0.15s;
    border-bottom: 1px solid rgba(255, 255, 255, 0.05);
    white-space: nowrap;
    letter-spacing: 1px;
    line-height: 1.5;
    
    &:active {
      background-color: rgba(179, 247, 60, 0.1);
    }
    
    &.delete {
      color: #ff5252;
    }
    
    .menu-icon {
      margin-right: 20rpx;
      font-size: 32rpx;
      width: 40rpx;
      text-align: center;
    }
  }
}

.context-menu-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9998;
  background-color: transparent;
}

/* 修改消息长按时的样式 */
.message-item {
  &:active {
    background-color: rgba(179, 247, 60, 0.05);
  }
}
</style> 